<?php
/**
 * 数据库操作类
 */
class Db 
{
	protected static $db;//放pdo链接对象
	protected $errorInfo=null;//放错误信息
	protected $table='';//表名
	protected $sql;//最后执行的语句
	protected $where = '';//条件
	protected $limit = '';//取部分
	protected $order = '';//排序
	// 产生pdo数据库连接对象，把表名存储在tabel
	public function __construct($table=null)
	{
		$this->table = $table;

		try{
			if(!self::$db){
				self::$db = @new PDO("mysql:host=".config('db_host').";dbname=".config('db_name').";charset=".config('db_charset'),config('db_user'),config('db_pass'));
			}
		}catch (PDOException $e) {
			$this->errorInfo = $e->getMessage();
		}
	}
	/**
	 * [getError 获取错误信息]
	 * @return [type] [description]
	 */
	public function getError()
	{
		return $this->errorInfo;
	}
	/**
	 * [getLastSql 最后执行sql]
	 * @return [type] [description]
	 */
	public function getLastSql()
	{
		return $this->sql;
	}
	/**
	 * [insert 增加]
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public function insert($data)
	{
		$keys = implode(",",array_keys($data));

		$values = implode("','",$data);

		$sql = "insert into ".$this->table." (".$keys.") values('".$values."')";

		return $this->exec($sql);		
	}
	/**
	 * [exec 执行增 删 改 sql]
	 * @param  [type] $sql [description]
	 * @return [type]      [description]
	 */
	public function exec($sql)
	{
		$this->sql=$sql;

		$res =  self::$db->exec($sql);

		if($res){
			return $res;
		}else{
			$this->errorInfo = self::$db->errorInfo();
			return false;
		}
	}
	//条件
	public function where($where)
	{
		$this->where = " where ".$where;
	}
	//取部分
	public function limit($limit)
	{
		$this->limit = " limit ".$limit;
	}
	//排序
	public function order($order)
	{
		$this->order = " order by ".$order;
	}
	/**
	 * [delete 删除]
	 * @return [type] [description]
	 */
	public function delete()
	{
		$sql = "delete from ".$this->table." ".$this->where;

		return $this->exec($sql);
	}
	/**
	 * [update 更新]
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public function update($data)
	{

		$str = '';

		foreach ($data as $k => $v) {
			$str .= $k ."='".$v."',";
		}

		$str = rtrim($str,',');

		$sql = "update ".$this->table." set ".$str." ".$this->where;

		return $this->exec($sql);

	}
	/**
	 * [select 查询]
	 * @param  string $field [description]
	 * @return [type]        [description]
	 */
	public function select($field="*")
	{
		$sql = "select ".$field." from ".$this->table.$this->where.$this->order.$this->limit;

		$this->sql = $sql;

		$resObj = self::$db->query($sql);

		if($resObj){
			return $resObj->fetchAll(PDO::FETCH_ASSOC);
		}else{
			$this->errorInfo = self::$db->errorInfo();
			return false;
		}
	}

}
